import { defineComponent, reactive, ref, computed, createVNode } from "vue";
import LForm, { LFormItem } from "@/components/public/lForm/lForm";
import styles from "./add.module.less";
import { $getAreaList } from "@/api/common/common";
import LPopup from "@/components/public/lPopup/lPopup";
import { useStore as useUserStore } from "@/store/user";
import {
  $groupOrderAdd,
  $getGroup,
  $groupOrderImport,
  $groupOrderValidate,
  $groupOrderCreate,
  $groupOrderCreateFaliedTask,
  $groupOrderCreateFaliedPeople
} from "@/api/groupOrder/groupOrder";
import {
  DoubleRightOutlined,
  CheckOutlined,
  InboxOutlined,
  ExclamationCircleOutlined,
} from "@ant-design/icons-vue";
import { message, UploadProps } from "ant-design-vue";
import { Modal } from "ant-design-vue";

export default defineComponent({
  emits: ["cancel", "confirm"],
  setup(props, { emit, expose }) {
    const userStore = useUserStore();
    const state = reactive({
      nextIndex: 0,
      listTitle: ["基础信息", "上传清单", "上传清单", "上传清单"],
      fileList: [],
      citylist: [],
      arealist: [],
      number: "",
      fileName: "",
      datalist: [],
      form: {
        applicant_name: "", //单位
        applicant_id_no: "", //证件号
        address: "", //单位地址
        applicant_mobile: "", //手机号
        contact_name: "", //姓名
        province_id: 933, //省份
        city_id: undefined, //市
        area_id: undefined, //区
      },
      columns: [
        {
          title: "续保/终保",
          dataIndex: ["is_new", "label"],
          key: "is_new",
          align: "center",
        },
        {
          title: "被保人姓名",
          dataIndex: "name",
          key: "name",
          align: "center",
        },
        {
          title: "证件类型",
          dataIndex: ["id_type", "label"],
          key: "id_type",
          align: "center",
        },
        {
          title: "证件号码",
          dataIndex: "id_no",
          key: "id_no",
          align: "center",
        },
        {
          title: "出生日期",
          dataIndex: "birthday",
          key: "birthday",
          align: "center",
        },
        {
          title: "性别",
          dataIndex: ["sex", "label"],
          key: "sex",
          align: "center",
        },
        {
          title: "手机号",
          dataIndex: "mobile",
          key: "mobile",
          align: "center",
        },
        {
          title: "所在市",
          dataIndex: ["city_id", "label"],
          key: "city_id",
          align: "center",
        },
        {
          title: "所在区县",
          dataIndex: ["area_id", "label"],
          key: "area_id",
          align: "center",
        },
        {
          title: "所在乡镇/街道",
          dataIndex: ["street_id", "label"],
          key: "street_id",
          align: "center",
        },
        {
          title: "所在村/社区",
          dataIndex: ["village_id", "label"],
          key: "village_id",
          align: "center",
        },
        {
          title: "商保/低保",
          dataIndex: ["people_type", "label"],
          align: "center",
          width: "180px",
        },
        {
          title: "生效时间",
          dataIndex: "start_date",
          key: "start_date",
          align: "center",
        },
        {
          title: "上传时间",
          dataIndex: "upload_date",
          key: "upload_date",
          align: "center",
        },
        {
          title: "处理结果",
          dataIndex: "status",
          key: "status",
          align: "center",
        },
        {
          title: "备注",
          dataIndex: "remark",
          key: "remark",
          align: "center",
        },
      ],
      pagination: {
        total: 0,
        current: 1,
        pageSize: 10,
      },
    } as any);
    const cancelHandler = () => {
      //提交投保人信息
      if (state.nextIndex == 0) {
        addPopupRef.value.close();
      } else if (state.nextIndex == 1) {
        state.nextIndex = 0;
      } else if (state.nextIndex == 2) {
        Modal.confirm({
          title: "提示",
          icon: createVNode(ExclamationCircleOutlined),
          content: "若返回上一步,需要重新上传文件,成功上传的内容将不会被保存",
          okText: "确认",
          cancelText: "取消",
          onOk: () => {
            state.fileList = [];
            state.fileName = "";
            state.nextIndex = 1;
          },
        });
      } else if (state.nextIndex == 3) {
        emit("confirm");
        addPopupRef.value.close();
      }
    };
    var hide: any;
    const confirmHandler = () => {
      //提交投保人信息
      if (state.nextIndex == 0) {
        $groupOrderAdd(state.form).then((res: any) => {
          state.number = res.data?.number || "";
          state.nextIndex = 1;
        });
      } else if (state.nextIndex == 1) {
        uploadFile();
      } else if (state.nextIndex == 2) {
        Modal.confirm({
          title: "提示",
          icon: createVNode(ExclamationCircleOutlined),
          content:
            "处理结果为“异常“情况时仍会录入,“失败”将不会录入,是否确认进行下一步",
          okText: "确认",
          cancelText: "取消",
          onOk: () => {
            state.loading = true;
            hide = message.loading('导入中', 0);
            $groupOrderCreate({ number: state.number }).then((res: any) => {
            }).catch(() => {
              setTimeout(hide);
            });
            searchResult();
          },
        });
      }
    };
    const searchResult = () => {
      $groupOrderCreate({ number: state.number }).then((res: any) => {
        if (res?.data?.status == 10) {
          searchResult();
        }
        else if (res?.data?.status == -1) {
          state.loading = false;
          setTimeout(hide);
          message.error("导入失败,请联系技术人员");
        }
        else if (res?.data?.status == 1) {
          state.loading = false;
          setTimeout(hide);
          message.success("导入成功");
          state.nextIndex = 3;
          if (res?.data?.download == true) {
            Modal.confirm({
              title: "提示",
              icon: createVNode(ExclamationCircleOutlined),
              content:
                "有部分信息未导入,是否下载重新导入",
              okText: "确认",
              cancelText: "取消",
              onCancel: () => {
                emit("confirm");
                addPopupRef.value.close();
              },
              onOk: () => {
                $groupOrderCreateFaliedTask({
                  number: state.number
                }).then((taskRes: any) => {
                  const interval = setInterval(() => {
                    const stopInterval = () => {
                      clearInterval(interval);
                    }
                    $groupOrderCreateFaliedPeople({
                      import_number: state.number,
                      number: taskRes.data?.number,
                    }).then((peopleRes: any) => {
                      if (peopleRes.data.status === 1) {
                        window.open(peopleRes.data.url);
                        state.fileList = [];
                        state.fileName = "";
                        state.nextIndex = 0;
                        stopInterval();
                      } else if(peopleRes.data.status === -1) {
                        emit("confirm");
                        addPopupRef.value.close();
                        stopInterval();
                      }
                    }).catch(() => {
                      emit("confirm");
                      addPopupRef.value.close();
                      stopInterval();
                    })
                  }, 1000)
                }).catch(() => {
                  emit("confirm");
                  addPopupRef.value.close();
                })
              },
            });
          }
        }
      });
    }
    //上传文件
    const uploadFile = () => {
      const formData: FormData = new FormData();
      formData.set("file", state.fileList[0].originFileObj);
      $groupOrderImport(
        { number: state.number },
        { file: state.fileList[0].originFileObj }
      ).then((res: any) => {
        state.nextIndex = 2;
        $groupOrderValidate({
          page: 1,
          limit: 10,
          number: state.number,
        }).then((res: any) => {
          state.pagination.total = res.data?.total;
          state.pagination.current = res.data?.current_page;
          state.pagination.pageSize = res.data?.per_page;
          state.datalist = res.data?.data || [];
        });
      });
    };
    //手动上传
    const beforeUpload: UploadProps["beforeUpload"] = (file) => {
      state.fileName = file.name;
      state.fileList = [file];
      return false;
    };
    // 表格状态变更
    const tableChangeHandler = (pag: { pageSize: number; current: number }) => {
      state.pagination.current = pag.current;
      state.pagination.pageSize = pag.pageSize;
      $groupOrderValidate({
        page: state.pagination.current,
        limit: state.pagination.pageSize,
        number: state.number,
      }).then((res: any) => {
        state.pagination.total = res.data?.total;
        state.datalist = res.data?.data || [];
      });
    };
    // 选中项变更
    const onSelectChange = (changableRowKeys: any[]) => {
      state.selectedRowKeys = changableRowKeys;
    };
    const rowSelection = computed(() => {
      return {
        selectedRowKeys: state.selectedRowKeys,
        fixed: true,
        onChange: onSelectChange,
      };
    });
    const addPopupRef = ref(null as any);
    const open = (e: any) => {
      //获取城市
      $getAreaList({}).then((res: any) => {
        res.data.forEach((item: any) => {
          if (item.id == state.form.province_id) {
            state.citylist = item.child.map((x: any) => {
              return {
                value: x.id,
                label: x.name,
                list: x.child,
              };
            });
          }
        });
      });
      state.nextIndex = 0;
      state.fileList = [];
      state.citylist = [];
      state.arealist = [];
      state.order_no = "";
      state.fileName = "";
      state.datalist = [];
      Object.keys(state.form).forEach((x: any) => {
        if (x != "province_id") {
          if (x == "city_id" || x == "area_id") {
            state.form[x] = undefined;
          } else {
            state.form[x] = "";
          }
        }
      });
      addPopupRef.value.open();
    };
    const close = () => {
      addPopupRef.value.close();
    };
    expose({
      open,
      close,
    });

    //基础信息
    const BasicInformation = () => (
      <LForm v-model={state.form}>
        <LFormItem label="投保单位名称" prop="">
          <a-input
            v-model:value={state.form.applicant_name}
            placeholder="请输入单位名称"
          ></a-input>
        </LFormItem>
        <LFormItem label="投保单位证件号" prop="">
          <a-input
            v-model:value={state.form.applicant_id_no}
            placeholder="请输入单位证件号"
          ></a-input>
        </LFormItem>
        <LFormItem label="投保单位地址" prop="">
          <a-input
            v-model:value={state.form.address}
            placeholder="请输入单位地址"
          ></a-input>
        </LFormItem>
        <LFormItem label="联系人姓名" prop="">
          <a-input
            v-model:value={state.form.contact_name}
            placeholder="请输入联系人姓名"
          ></a-input>
        </LFormItem>
        <LFormItem label="联系人手机号" prop="">
          <a-input
            v-model:value={state.form.applicant_mobile}
            placeholder="请输入联系人手机号"
          ></a-input>
        </LFormItem>
        <LFormItem label="所在市" prop="">
          <a-select
            v-model:value={state.form.city_id}
            options={state.citylist}
            placeholder="请选择所在市"
            style="width:100%"
            onChange={(e: any, option: any) => {
              state.form.area_id = undefined;
              state.arealist = option.list.map((x: any) => {
                return {
                  value: x.id,
                  label: x.name,
                };
              });
            }}
          ></a-select>
        </LFormItem>
        <LFormItem label="所在区/县" prop="">
          <a-select
            v-model:value={state.form.area_id}
            options={state.arealist}
            placeholder="请选择所在区/县"
            style="width:100%"
          ></a-select>
        </LFormItem>
      </LForm>
    );
    //上传清单
    const UploadChecklist = () => (
      <div class={styles.uploadChecklist_box}>
        <div class={styles.head_box}>
          <div class={styles.head_left_box}>
            {state.nextIndex > 1 ? (
              <div class={styles.number_select_box}>
                <CheckOutlined />
              </div>
            ) : (
              <div
                class={[
                  styles.numberOne_box,
                  state.nextIndex < 1 && styles.numberOne_current_box,
                ]}
              >
                1
              </div>
            )}
            <div class={styles.content_box}>
              <div class={styles.label_box}>导入清单文件</div>
              {/* <div class={styles.comment_text_box}>上传被保人信息</div> */}
            </div>
          </div>
          <div class={styles.icon_box}>
            <DoubleRightOutlined />
          </div>
          <div class={styles.head_left_box}>
            {state.nextIndex > 2 ? (
              <div class={styles.number_select_box}>
                <CheckOutlined />
              </div>
            ) : (
              <div
                class={[
                  styles.numberOne_box,
                  state.nextIndex < 2 && styles.numberOne_current_box,
                ]}
              >
                2
              </div>
            )}
            <div class={styles.content_box}>
              <div class={styles.label_box}>确认上传结果</div>
              {/* <div class={styles.comment_text_box}>上传被保人信息</div> */}
            </div>
          </div>
          <div class={styles.icon_box}>
            <DoubleRightOutlined />
          </div>
          <div class={styles.head_left_box}>
            <div
              class={[
                styles.numberOne_box,
                state.nextIndex < 3 && styles.numberOne_current_box,
              ]}
            >
              3
            </div>
            <div class={styles.content_box}>
              <div class={styles.label_box}>上传成功</div>
              {/* <div class={styles.comment_text_box}>上传被保人信息</div> */}
            </div>
          </div>
        </div>
        <div class={styles.body_box}>
          {state.nextIndex == 1 && (
            <div class={styles.content_box}>
              <div class={styles.content_head_box}>
                <a-button
                  type="primary"
                  size="small"
                  onClick={() => {
                    $getGroup({}).then((res: any) => {
                      window.open(res.data.url);
                    });
                  }}
                >
                  下载模版
                </a-button>
                <div class={styles.content_label_box}>点击下载团单模版</div>
              </div>
              <div class={styles.uploadBox}>
                <a-upload-dragger
                  v-model:fileList={state.fileList}
                  name="file"
                  before-upload={beforeUpload}
                  showUploadList={false}
                >
                  <p class="ant-upload-drag-icon">
                    <InboxOutlined></InboxOutlined>
                  </p>
                  {state.fileName ? (
                    <p class="ant-upload-text">{state.fileName}</p>
                  ) : (
                    <p class="ant-upload-text">点击或将文件拖拽到这里上传</p>
                  )}
                </a-upload-dragger>
              </div>
            </div>
          )}
          {state.nextIndex > 1 && (
            <div class={styles.group_box}>
              {state.nextIndex == 3 && (
                <div class={styles.group_order_box}>
                  <div class={styles.group_order_round_box}>
                    <CheckOutlined />
                  </div>
                  <div class={styles.group_order_label_box}>团单添加成功</div>
                </div>
              )}
              <Grouplist />
            </div>
          )}
        </div>
      </div>
    );
    //上传团单列表结果
    const Grouplist = () => (
      <div style={{ width: "100%" }}>
        <a-table
          dataSource={state.datalist}
          columns={state.columns}
          pagination={state.pagination}
          scroll={{ x: 2000 }}
          onChange={tableChangeHandler}
          v-slots={{
            bodyCell: ({ column, record }: any) => {
              if (column.dataIndex == "status") {
                if (record.status.value == "1") {
                  return (
                    <div style={{ color: "green" }}>{record.status.label}</div>
                  );
                } else {
                  return (
                    <div style={{ color: "red" }}>{record.status.label}</div>
                  );
                }
              }
            },
          }}
        />
      </div>
    );
    const Components = () => (
      <LPopup
        title={state.listTitle[state.nextIndex]}
        ref={addPopupRef}
        width={state.nextIndex > 1 ? "1000px" : "800px"}
      >
        <div class={styles.orderEntryAdd}>
          {state.nextIndex == 0 && <BasicInformation />}
          {state.nextIndex > 0 && <UploadChecklist />}
          <div class={styles.btn_Box}>
            <a-button
              size="small"
              style={{ width: "55px" }}
              onClick={() => cancelHandler()}
            >
              {state.nextIndex == 3
                ? "关闭"
                : state.nextIndex == 0
                  ? "取消"
                  : "上一步"}
            </a-button>
            {state.nextIndex != 3 && (
              <div class={styles.right_btn_box}>
                <a-button
                  type="primary"
                  size="small"
                  loading={state.loading}
                  onClick={() => confirmHandler()}
                >
                  下一步
                </a-button>
              </div>
            )}
          </div>
        </div>
      </LPopup>
    );
    return {
      Components,
    };
  },
  render() {
    return <this.Components />;
  },
});
